const koa = require('koa');
const http = require('http');
const chokidar = require('chokidar');
const serveStaticPlugin = require('./plugin/serverPluginServeStatic');
const moduleRewritePlugin = require('./plugin/serverPluginModuleRewrite');
const moduleResolvePlugin = require('./plugin/serverPluginModuleResolve');
const { vuePlugin } = require('./plugin/serverPluginVue');
const imagePlugin = require('./plugin/serverPluginImage');
const { stylePlugin } = require('./plugin/serverPluginStyle');
const { clientPlugin } = require('./plugin/serverPluginClient');
const hmrPlugin = require('./plugin/serverPluginHmr');
const htmlRewritePlugin = require('./plugin/serverPluginHtml');

function resolveServer(requestListener) {
  return http.createServer(requestListener);
}

const serverPort = 3003;

function createServer() {
  let app = new koa();

  const server = resolveServer(app.callback());

  const root = process.cwd();

  const watcher = chokidar.watch(root, {
    ignored: [/\/\.node_modules\//, /\/\.git\//, /\/\vite\//],
    awaitWriteFinish: {
      stabilityThreshold: 100,
      pollInterval: 10
    }
  })

  const context = {
    app,
    root,
    server,
    watcher,
    port: serverPort
  }

  resolvedPlugins = [
    moduleRewritePlugin, // 重写模块
    htmlRewritePlugin, // 重写html
    moduleResolvePlugin, // 找到node_modules 所对应的依赖
    clientPlugin, // 热更新 客户端
    hmrPlugin, // 热更新 服务端
    vuePlugin, // 处理.vue 文件
    imagePlugin, // 图片
    stylePlugin, // css
    serveStaticPlugin, // 静态服务
  ];

  resolvedPlugins.forEach(plugin => plugin(context));

  return server;
}

createServer().listen(serverPort, () => {
  console.log('vite start')
})